"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.MiniLayout = void 0;

var _taro = _interopRequireDefault(require("@tarojs/taro"));

var _classnames = _interopRequireDefault(require("classnames"));

var _react = _interopRequireWildcard(require("react"));

var _components = require("@tarojs/components");

var _configContext = require("../../../../extends/configContext");

var _icon = _interopRequireDefault(require("../../../../components/icon"));

var _progress = _interopRequireDefault(require("../../../progress"));

var _toast = _interopRequireDefault(require("../../../../components/toast"));

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }

function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }

function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }

function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }

function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized(self); }

function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }

function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }

function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

// 无注释，未考虑边界情况，满足了业务再优化
var MiniLayout = /*#__PURE__*/function (_Component) {
  _inherits(MiniLayout, _Component);

  var _super = _createSuper(MiniLayout);

  function MiniLayout(props) {
    var _this;

    _classCallCheck(this, MiniLayout);

    _this = _super.call(this, props);

    _defineProperty(_assertThisInitialized(_this), "recorderManager", null);

    _defineProperty(_assertThisInitialized(_this), "intervalId", null);

    _defineProperty(_assertThisInitialized(_this), "needToUpload", false);

    _defineProperty(_assertThisInitialized(_this), "needToCancel", false);

    _this.state = {
      isRecording: false,
      precent: 0,
      second: 0,
      file: null
    };
    return _this;
  }

  _createClass(MiniLayout, [{
    key: "authorizeRecord",
    value: function authorizeRecord() {
      var _this2 = this;

      _taro.default.authorize({
        scope: 'scope.record',
        success: function success() {
          _this2.startRecord();
        },
        fail: function fail(err) {
          var _err$errMsg;

          if ((err === null || err === void 0 ? void 0 : (_err$errMsg = err.errMsg) === null || _err$errMsg === void 0 ? void 0 : _err$errMsg.indexOf('auth deny')) > -1) {
            _toast.default.info({
              content: '请在小程序页面右上角 - 更多 - 设置里允许小程序使用录音权限',
              duration: 3000
            });
          }
        }
      });
    }
  }, {
    key: "startRecord",
    value: function startRecord() {
      var _this3 = this;

      var _this$state = this.state,
          isRecording = _this$state.isRecording,
          file = _this$state.file;
      var _this$props = this.props,
          _this$props$onRecordB = _this$props.onRecordBegan,
          onRecordBegan = _this$props$onRecordB === void 0 ? function () {} : _this$props$onRecordB,
          _this$props$onRecordC = _this$props.onRecordCompleted,
          onRecordCompleted = _this$props$onRecordC === void 0 ? function () {} : _this$props$onRecordC;
      if (isRecording || file) return;
      var _this$props$duration = this.props.duration,
          duration = _this$props$duration === void 0 ? 60 : _this$props$duration;
      this.recorderManager = _taro.default.getRecorderManager();
      this.recorderManager.onStart(function () {
        _this3.setState({
          isRecording: true
        });

        _this3.onRecordStart();

        onRecordBegan();
      });
      this.recorderManager.onStop(function (res) {
        if (_this3.needToCancel) {
          _this3.resetRecord();

          _this3.needToCancel = false;
          return;
        }

        onRecordCompleted();

        _this3.setState({
          file: res,
          isRecording: false
        });

        if (_this3.needToUpload) _this3.props.onUpload(_this3.state.file);
        _this3.needToUpload = false;
      });
      this.recorderManager.start({
        duration: duration * 1000,
        sampleRate: 44100,
        numberOfChannels: 1,
        encodeBitRate: 192000,
        format: 'mp3'
      });
    }
  }, {
    key: "stopRecord",
    value: function stopRecord() {
      this.recorderManager.stop();
      clearInterval(this.intervalId);
    }
  }, {
    key: "cancelRecord",
    value: function cancelRecord() {
      var file = this.state.file;
      var _this$props$onRecordR = this.props.onRecordReset,
          onRecordReset = _this$props$onRecordR === void 0 ? function () {} : _this$props$onRecordR;
      this.stopRecord();
      onRecordReset();

      if (file) {
        this.resetRecord();
      } else {
        this.needToCancel = true;
      }
    }
  }, {
    key: "resetRecord",
    value: function resetRecord() {
      this.setState({
        isRecording: false,
        precent: 0,
        second: 0,
        file: null
      });
    }
  }, {
    key: "uploadRecord",
    value: function uploadRecord() {
      var file = this.state.file;
      this.stopRecord();
      if (file) this.props.onUpload(file);else this.needToUpload = true;
    }
  }, {
    key: "onRecordStart",
    value: function onRecordStart() {
      var _this4 = this;

      var _this$props$duration2 = this.props.duration,
          duration = _this$props$duration2 === void 0 ? 60 : _this$props$duration2;
      duration = duration * 1000;
      var beginTime = new Date().getTime();
      var endTime = beginTime + duration;
      this.intervalId = setInterval(function () {
        var nowTime = new Date().getTime();

        _this4.setState({
          precent: Math.floor((nowTime - beginTime) / duration * 100),
          second: Math.floor((nowTime - beginTime) / 1000)
        });

        if (nowTime >= endTime) {
          _this4.stopRecord();
        }
      }, 500);
    }
  }, {
    key: "render",
    value: function render() {
      var clsPrefix = this.context.clsPrefix;
      var _this$state2 = this.state,
          isRecording = _this$state2.isRecording,
          precent = _this$state2.precent,
          second = _this$state2.second,
          file = _this$state2.file;
      var clsModule = "".concat(clsPrefix, "-audio-record");
      var hz = Array(9).fill('').map(function (_item, index) {
        var defaultClass = "".concat(clsModule, "-area-hz-").concat(index + 1);
        var animationClass = "".concat(clsModule, "-area-hz-").concat(index + 1, "--animation");
        return /*#__PURE__*/_react.default.createElement(_components.View, {
          className: (0, _classnames.default)(defaultClass, _defineProperty({}, animationClass, isRecording))
        });
      });
      return /*#__PURE__*/_react.default.createElement(_components.View, {
        className: clsModule
      }, (isRecording || file) && /*#__PURE__*/_react.default.createElement(_components.Text, {
        className: "".concat(clsModule, "-duration")
      }, "".concat(second, "S")), /*#__PURE__*/_react.default.createElement(_components.View, {
        className: "".concat(clsModule, "-area")
      }, /*#__PURE__*/_react.default.createElement(_components.View, {
        className: "".concat(clsModule, "-area-hz")
      }, hz), /*#__PURE__*/_react.default.createElement(_components.View, {
        className: "".concat(clsModule, "-area-btn"),
        onClick: this.authorizeRecord.bind(this)
      }, /*#__PURE__*/_react.default.createElement(_progress.default, {
        type: "circle",
        percent: precent,
        lineWidth: 3,
        isShowText: false,
        className: "progress-circle-width"
      }, /*#__PURE__*/_react.default.createElement(_components.View, {
        className: "".concat(clsModule, "-area-btn-status")
      }, isRecording || file ? /*#__PURE__*/_react.default.createElement(_components.View, {
        className: "".concat(clsModule, "-area-btn-status-icon")
      }) : /*#__PURE__*/_react.default.createElement(_icon.default, {
        name: "MicroOutlined",
        size: 20
      })))), /*#__PURE__*/_react.default.createElement(_components.View, {
        className: "".concat(clsModule, "-area-hz")
      }, [].concat(hz).reverse())), /*#__PURE__*/_react.default.createElement(_components.View, {
        className: "".concat(clsModule, "-toolbar")
      }, isRecording || file ? /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_icon.default, {
        className: "".concat(clsModule, "-toolbar-text"),
        name: "ReturnOutlined",
        size: 16,
        onClick: this.cancelRecord.bind(this)
      }), /*#__PURE__*/_react.default.createElement(_components.Text, {
        className: "".concat(clsModule, "-toolbar-tips")
      }, file ? '录制完成' : '录制中'), /*#__PURE__*/_react.default.createElement(_icon.default, {
        className: "".concat(clsModule, "-toolbar-text"),
        name: "CheckOutlined",
        size: 16,
        onClick: this.uploadRecord.bind(this)
      })) : /*#__PURE__*/_react.default.createElement(_components.Text, {
        className: "".concat(clsModule, "-toolbar-tips")
      }, "\u70B9\u51FB\u5F55\u97F3")));
    }
  }]);

  return MiniLayout;
}(_react.Component);

exports.MiniLayout = MiniLayout;

_defineProperty(MiniLayout, "contextType", _configContext.ConfigContext);